﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Http;

using ERPStore.Extensions;

namespace ERPStore.Exporter.Services
{
	public class ShopzillaService
	{
		public ShopzillaService(ERPStore.Services.ICacheService cacheService)
		{
			this.CacheService = cacheService;
		}

		protected ERPStore.Services.ICacheService CacheService { get; private set; }

		public List<Models.ShopzillaCategory> GetCategories()
		{
			var list = CacheService["ShopzillaCategoryList"] as List<Models.ShopzillaCategory>;
			if (list == null)
			{
				GererateTaxonomy();
			}
			return list;
		}

		public static void GererateTaxonomy()
		{
			var path = Configuration.ConfigurationSettings.AppSettings["exportPath"];
			var taxonomyFileName = string.Format("{0}.xml", System.IO.Path.Combine(path, "shopzilla.taxonomy"));

			if (System.IO.File.Exists(taxonomyFileName))
			{
				var serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<Models.ShopzillaCategory>));
				using (var fs = System.IO.File.OpenRead(taxonomyFileName))
				{
					var list = (List<Models.ShopzillaCategory>)serializer.Deserialize(fs);
					fs.Flush();
					var cacheService = GlobalConfiguration.Configuration.DependencyResolver.GetService<ERPStore.Services.ICacheService>();
					cacheService.Add("ShopzillaCategoryList", list, DateTime.Now.AddDays(1));
				}
			}
			else
			{
				var pg = CloudSoft.Workflows.ProgressReporterCollector.Get("7C968916-54A8-4544-9413-E1FC1D043765");
				if (pg == null)
				{
					pg = CloudSoft.Workflows.ProgressReporterCollector.GetNew();
					pg.Id = "7C968916-54A8-4544-9413-E1FC1D043765";
					CloudSoft.Workflows.WorkflowQueueUserWorkItem.RunAsync(
						new Workflows.Activities.GenerateShopzillaTaxonomy()
						, null
						, pg
					);
				}
			}
		}
	}
}
